<?php

declare(strict_types=1);
/**
 * 创建人 : Forpastime
 *
 * @link     http://hypercmf.com
 * @document https://hyperf.wiki
 * @contact  forpastime@qq.com
 * @git  https://gitee.com/hypercmf/hypercmf1.0.git
 */
namespace App\Middleware\Auth;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext;

/**
 * 后端请求path_info鉴权
 *
 * Class AdminPowerMiddleware
 * @package App\Middleware\Auth
 */
class AdminPowerMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var HttpResponse
     */
    protected $response;


    /**
    * @param HttpResponse $response 注意这里的response 是 ResponseInterface 是hyperf
    * @param RequestInterface $request 注意这里的request 是 RequestInterface  是hyperf
    */
    public function __construct(ContainerInterface $container, HttpResponse $response)
    {
        $this->container = $container;
        $this->response = $response;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $serverParam = $request->getServerParams();
        $token = $request->getHeader('token');
        $admin = explode('_',$token[0]);
        $path = $serverParam['path_info'];
        $redis = ApplicationContext::getContainer()->get(Redis::class);
        $roleId = $redis->get('HyperCMF:admin_role:'.$admin[0]);
        if($roleId==1){
            return $handler->handle($request);
        }
        if(!$redis->get('HyperCMF:menu_power_routes:'.$roleId)){
            return $this->response->json(
                [
                    'code' => -1,
                    'data' => [],
                    'msg' => '该用户角色尚未分配权限！',
                ]
            );
        }
        if(!in_array($path,explode(',',$redis->get('HyperCMF:menu_power_routes:'.$roleId)))){
            return $this->response->json(
                [
                    'code' => -1,
                    'data' => [],
                    'msg' => '您暂无操作权限！',
                ]
            );
        }
        return $handler->handle($request);
    }
}